<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>实现全选功能</title>
	</head>
	<body>
		<p>你的爱好是<input type="checkbox"  id="checedAllBox" />全选 / 全不选</p> 
		<input type="checkbox" name="items" value="足球"  />足球
		<input type="checkbox" name="items" value="篮球"/>篮球
		<input type="checkbox" name="items" value="羽毛球" />羽毛球
		<input type="checkbox" name="items"  value="乒乓球"/>乒乓球
		<br>
		<button type="button" id="checkedAllBtn">全选</button>
		<button type="button" id="checkedNoBtn">全不选</button>
		<button type="button" id="checkedRevBtn">反选</button>
		<button type="button" id="sendBtn">提交</button>
		<script type="text/javascript">
			window.onload = function(){
				var  checkedAllBtn = document.getElementById("checkedAllBtn");
				var checedAllBox = document.getElementById("checedAllBox");
				var items = document.getElementsByName("items");//获取input里面name属性
				checkedAllBtn.onclick = function(){/* 全选 */
					/* 获取多选框   都有name属性*/
					for(var i = 0 ; i < items.length ;i++){
						/* checked="checked" 表示选中*/
						items[i].checked = true ;
						if(items[i].checked){
							checedAllBox.checked = true;
						}
					}
					
				}
				checedAllBox.onclick = function(){
					for(var i = 0 ; i < items.length ;i++){
						/* checked="checked" 表示选中*/
						/* if(checedAllBox.checked){
							items[i].checked = true ;
						} else {
							items[i].checked = false;
						} */
						items[i].checked=this.checked ;
						
						
					}
					
				}
				for(var i = 0 ; i < items.length; i++){
					items[i].onclick = function(){
						checedAllBox.checked = true ;
						for(var j = 0 ; j <items.length ; j++){
							if(items[j].checked == false){
								checedAllBox.checked = false ;
							} 
						}
					
					}
				}
				
				checkedNoBtn.onclick = function(){/* 全不選 */
					/* 获取多选框   都有name属性*/
					
					for(var i = 0 ; i < items.length ;i++){
						/* checked="checked" 表示选中*/
						items[i].checked = false;
						if(!items[i].checked){
							checedAllBox.checked = false;
						}
					}
				}
				checkedRevBtn.onclick = function(){/* 反选 */
					for(var i = 0 ; i < items.length ;i++){
					/* 	
						if(items[i].checked){
							items[i].checked = false;
						} else {
							items[i].checked = true ;
						} */
						items[i].checked = 	!items[i].checked 
					}
				}
				sendBtn.onclick = function(){
					for(var i = 0 ; i < items.length ;i++){
						/* checked="checked" 表示选中*/
						if(items[i].checked){
							alert(items[i].value);
						}
					
						
					}
					
				}
			}
		</script>
	</body>
</html>
